package com.kele.pay.service;

import com.github.wxpay.sdk.WXPayUtil;
import com.kele.common.model.response.Result;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WxPayService {

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.partner}")
    private String partner;

    @Value("${weixin.partnerkey}")
    private String partnerkey;

    @Value("${weixin.notifyurl}")
    private String notifyurl;

    public Result unifiedOrder(Long orderId, Integer total_fee, String body) throws Exception {

        //1 初始化OkHttpClient  postman
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/xml");
        //准备接口参数
        Map<String,String> map = new HashMap<>();
        map.put("appid",appid);
        map.put("mch_id",partner);
        map.put("nonce_str",WXPayUtil.generateNonceStr());

        map.put("body",body);
        map.put("out_trade_no",orderId.toString());
        map.put("total_fee",total_fee.toString());
        map.put("spbill_create_ip","127.0.0.1");
        map.put("notify_url",notifyurl);
        map.put("trade_type","NATIVE");

        String content = WXPayUtil.generateSignedXml(map, partnerkey);
        System.out.println(content);

        RequestBody requestBody = RequestBody.create(mediaType,content);
        //2 创建Request
        Request request = new Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/unifiedorder")
                .post(requestBody)
                .build();

        //3.获取Call对象，Call可以同步调用，也可以异步调用
        Call call = okHttpClient.newCall(request);
        //4.同步发送HTTP请求返回响应
        Response response = call.execute();//同步调用

        int code = response.code();//200
        String message = response.message();
        String protocol = response.protocol().toString();
        System.out.println("code=" + code);
        System.out.println("message=" + message);
        System.out.println("protocol=" + protocol);

        ResponseBody responseBody = response.body();
        String response_body_xml = responseBody.string();
        System.out.println("response_body_xml=" + response_body_xml);

        Map<String, String> stringStringMap = WXPayUtil.xmlToMap(response_body_xml);

        String return_code = stringStringMap.get("return_code");
        String err_code_des = stringStringMap.get("err_code_des");
        if(!StringUtils.isEmpty(return_code) && return_code.equals("SUCCESS")){
            String result_code = stringStringMap.get("result_code");
            if(!StringUtils.isEmpty(result_code) && result_code.equals("SUCCESS")){
                String code_url = stringStringMap.get("code_url");
                return new Result(true,"1",code_url);
            }
        }
        return new Result(false,"0",err_code_des);
    }

    public Result orderQuery(Long orderId) throws Exception {
        //1 初始化OkHttpClient  postman
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/xml");
        //准备接口参数
        Map<String,String> map = new HashMap<>();
        map.put("appid",appid);
        map.put("mch_id",partner);
        map.put("out_trade_no",orderId.toString());
        map.put("nonce_str",WXPayUtil.generateNonceStr());

        String content = WXPayUtil.generateSignedXml(map, partnerkey);

        System.out.println(content);

        RequestBody requestBody = RequestBody.create(mediaType,content);
        //2 创建Request
        Request request = new Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/orderquery")
                .post(requestBody)
                .build();

        //3.获取Call对象，Call可以同步调用，也可以异步调用
        Call call = okHttpClient.newCall(request);
        //4.同步发送HTTP请求返回响应
        Response response = call.execute();//同步调用

        int code = response.code();//200
        String message = response.message();
        String protocol = response.protocol().toString();
        System.out.println("code=" + code);
        System.out.println("message=" + message);
        System.out.println("protocol=" + protocol);

        ResponseBody responseBody = response.body();
        String response_body_xml = responseBody.string();
        System.out.println("response_body_xml=" + response_body_xml);

        Map<String, String> stringStringMap = WXPayUtil.xmlToMap(response_body_xml);

        String return_code = stringStringMap.get("return_code");
        if(!StringUtils.isEmpty(return_code) && return_code.equals("SUCCESS")){
            String result_code = stringStringMap.get("result_code");
            String trade_state  = stringStringMap.get("trade_state");
            String trade_state_desc  = stringStringMap.get("trade_state_desc");
            if(!StringUtils.isEmpty(result_code) && result_code.equals("SUCCESS")
                && !StringUtils.isEmpty(trade_state) && trade_state.equals("SUCCESS")){
                /**
                 * SUCCESS--支付成功
                 * REFUND--转入退款
                 * NOTPAY--未支付
                 * CLOSED--已关闭
                 * REVOKED--已撤销(刷卡支付)
                 * USERPAYING--用户支付中
                 * PAYERROR--支付失败(其他原因，如银行返回失败)
                 * ACCEPT--已接收，等待扣款
                 */
                System.out.println("修改订单的状态。。。");
                return new Result(true,"1",trade_state_desc);
            }else {
                return new Result(false,"0",trade_state_desc);
            }
        }
        return Result.FAIL();
    }
}
